package com.manlitech.manlichat.base.redis.scenes;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis 应用场景
 */
@Component
public class RedisScenes {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    RedisTemplate redisTemplate;

    /**
     *
     * @param ip
     * @param expireSecond 失效时间 （秒）
     * @param limitMaxCount ip单位时间访问最大值
     * @return
     */
    public boolean calculateIpCount(String ip , Integer expireSecond ,Integer limitMaxCount){
        //设置序列化类使用GenericToStringSerializer为了可以使用increment这个方法
        GenericToStringSerializer genericToStringSerializer = new GenericToStringSerializer(Object.class);
        redisTemplate.setValueSerializer(genericToStringSerializer);
        //获取当前IP访问次数
        Object currentIpCount = redisTemplate.opsForValue().get(ip);
        if(currentIpCount == null){
            //第一次访问设置1
            redisTemplate.opsForValue().set(ip,"1",expireSecond, TimeUnit.SECONDS);
        }else{
            int currentIpCountInteger = Integer.valueOf(currentIpCount.toString());
            if(limitMaxCount != null){
                if(currentIpCountInteger >= limitMaxCount){
                    logger.error("IP[{}]在[{}]单位时间内请求满足上限[{}]",ip,expireSecond,limitMaxCount);
                    return true;
                }else{
                    redisTemplate.opsForValue().increment(ip);
                }
            }else{
                return true;
            }
        }
        return false;
    }

    /**
     * 一条消息一次消费
     */
    public void pubOneOffMsg(String queueName , JSONObject msg){
        redisTemplate.opsForList().leftPush(queueName, msg.toString());
    }

    public JSONObject subOneOffMsg(String queueName ){
        if(redisTemplate.opsForList().size(queueName) == 0){
            return null;
        }
        String msg = redisTemplate.opsForList().rightPop(queueName).toString();
        JSONObject object = JSONObject.parseObject(msg);
        return object;
    }




}
